import React from 'react';
import PropTypes from 'prop-types';
import Section from '../../components/Section';
import { keys, groupBy, get } from 'lodash';
import { TextField } from 'office-ui-fabric-react';

const renderGroup = (group, fields) => (
  <Section
    title={group}
    key={group}
    style={{ flexDirection: 'row', flexWrap: 'wrap', display: 'flex' }}
  >
    {fields.map((field, index) => {
      return (
        <TextField
          styles={{ root: { margin: '5px' } }}
          name={field.name}
          label={field.label}
          key={index}
          underlined
        />
      );
    })}
  </Section>
);

const FormPreviewer = ({ fields, grouping }) => {
  if (!grouping) return renderGroup('', fields);
  else {
    const groupedFields = groupBy(fields, 'group');
    return keys(groupedFields).map(group => {
      const items = get(groupedFields, group, []);
      return renderGroup(group, items);
    });
  }
};

FormPreviewer.propTypes = {
  fields: PropTypes.array,
  grouping: PropTypes.bool
};

FormPreviewer.defaultProps = {
  fields: [],
  grouping: true
};

export default FormPreviewer;
